package lemon.kenhnhacvn;
//
//import android.support.v7.app.ActionBarActivity;
//import android.support.v7.app.ActionBar;
//import android.support.v4.app.Fragment;
//import android.os.Bundle;
//import android.view.LayoutInflater;
//import android.view.Menu;
//import android.view.MenuItem;
//import android.view.View;
//import android.view.ViewGroup;
//import android.os.Build;
//
//
//
//public class MainActivity extends ActionBarActivity {
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//        if (savedInstanceState == null) {
//            getSupportFragmentManager().beginTransaction()
//                    .add(R.id.container, new PlaceholderFragment())
//                    .commit();
//        }
//    }
//
//
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.main, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//        if (id == R.id.action_settings) {
//            return true;
//        }
//        return super.onOptionsItemSelected(item);
//    }
//
//    /**
//     * A placeholder fragment containing a simple view.
//     */
//    public static class PlaceholderFragment extends Fragment {
//
//        public PlaceholderFragment() {
//        }
//
//        @Override
//        public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                Bundle savedInstanceState) {
//            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//            return rootView;
//        }
//    }
//}
import java.util.ArrayList;

import saucaca.Object.PlaylistObject;
import saucaca.Object.SongObject;
import saucaca.Service.MusicService;
import saucaca.Service.MusicService.MediaPlayerState;
import saucaca.Service.PlaylistManager;
import saucaca.Service.PlaylistManager.RepeatMode;
import saucaca.Service.Singleton;
import saucaca.Slidingmenu.SlidingMenu;
import saucaca.Slidinguppanel.SlidingUpPanelLayout;
import saucaca.Slidinguppanel.SlidingUpPanelLayout.PanelSlideListener;
import saucaca.Util.CirclePageIndicator;
import saucaca.Util.PageIndicator;
import saucaca.Util.TagName;
import saucaca.Util.UtilMusic;
import saucaca.fragment.CommentFragment;
import saucaca.fragment.MainListeningPlaylistQueue;
import saucaca.fragment.MainListteningContent;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends BaseActivity {
	String TAG = MainActivity.class.getSimpleName();
	ImageView imgMenuNavigate;
	private TextView playing_Title, txtSong, playing_Artist, txtSinger;
	private TextView currentPlayingPosition;
	private TextView currentDuration;
	private TextView currentPlayingPosition1;
	private TextView currentDuration1;
	private ImageView bt_Play, controlPlay;
	private ImageView bt_Next, controlNext;
	private ImageView bt_Previous, controlPrev;
	private ImageView bt_ShuffleToggle;
	private ImageView bt_RepeatToggle, imgMini_album;

	private SeekBar songProgressBar;
	private SeekBar songProgressBar1;
	private boolean songProgressBarIsBeingTouch;
	public PlaylistManager mPlaylistMgr;
	private MusicServiceStatusReceiver mStatusReceiver;

	ViewPager viewPager;
	CirclePageIndicator mIndicator;
	OfflineTabPageAdapter TabAdapter;

	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initView();
		// BaseEngine.getKeyHashes(getApplicationContext());
	};

	private void initView() {
		mSilidingUP = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
		showPanelControl(false);
		mSilidingUP.setPanelSlideListener(new PanelSlideListener() {
			@SuppressLint("NewApi")
			@Override
			public void onPanelSlide(View panel, float slideOffset) {
				controllayout.setAlpha(1 - slideOffset);
				controllayout2.setAlpha(slideOffset);
				controllayout2.setVisibility(View.VISIBLE);
			}

			@Override
			public void onPanelExpanded(View panel) {
				setSlideEnable(false);
			}

			@Override
			public void onPanelCollapsed(View panel) {
				Log.i(TAG, "onPanelCollapsed");
				setSlideEnable(true);
				controllayout2.setVisibility(View.GONE);
			}

			@Override
			public void onPanelAnchored(View panel) {
				Log.i(TAG, "onPanelAnchored");
			}

			@Override
			public void onPanelHidden(View panel) {
				Log.i(TAG, "onPanelHidden");
				controllayout2.setVisibility(View.GONE);
			}
		});
		
		imgMini_album = (ImageView) findViewById(R.id.mini_picture_control);
//		 imgMini_album.startAnimation(AlbumAnimation);

		imgMenuNavigate = (ImageView) findViewById(R.id.menu_top_navigation_back);
		imgMenuNavigate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSilidingUP.collapsePanel();
			}
		});
		controlPlay = (ImageView) findViewById(R.id.btn_play);
		controlPrev = (ImageView) findViewById(R.id.btn_pre);
		controlNext = (ImageView) findViewById(R.id.btn_next);

		bt_Play = (ImageView) findViewById(R.id.listening_control_imagePlayPause);
		bt_Previous = (ImageView) findViewById(R.id.listening_control_imagePrevious);
		bt_Next = (ImageView) findViewById(R.id.listening_control_imageNext);
		bt_ShuffleToggle = (ImageView) findViewById(R.id.listening_control_imageShuffle);
		bt_RepeatToggle = (ImageView) findViewById(R.id.listening_control_imageRepeat);
		txtSong = (TextView) findViewById(R.id.txt_song);
		txtSinger = (TextView) findViewById(R.id.txt_singer);
		playing_Title = (TextView) findViewById(R.id.title_of_nameSong);
		playing_Artist = (TextView) findViewById(R.id.title_of_artist);
		currentPlayingPosition = (TextView) findViewById(R.id.listening_control_textbufferStart);
		currentDuration = (TextView) findViewById(R.id.listening_control_textbufferEnd);
		currentPlayingPosition1 = (TextView) findViewById(R.id.listening_control_textbufferStart1);
		currentDuration1 = (TextView) findViewById(R.id.listening_control_textbufferEnd1);

		songProgressBarIsBeingTouch = false;
		songProgressBar1 = (SeekBar) findViewById(R.id.listening_control_seekBars1);
		songProgressBar1.setMax(100);
		songProgressBar1.setOnSeekBarChangeListener(songProgressBar_changeListener);
		songProgressBar = (SeekBar) findViewById(R.id.listening_control_seekBars);
		songProgressBar.setMax(100);
		songProgressBar.setOnSeekBarChangeListener(songProgressBar_changeListener);
		controlPrev.setOnClickListener(bt_Previous_click);
		controlPlay.setOnClickListener(bt_Play_click);
		controlNext.setOnClickListener(bt_Next_click);

		bt_Previous.setOnClickListener(bt_Previous_click);
		bt_Play.setOnClickListener(bt_Play_click);
		bt_Next.setOnClickListener(bt_Next_click);
		bt_ShuffleToggle.setOnClickListener(bt_ShuffleToggle_Click);
		bt_RepeatToggle.setOnClickListener(bt_RepeatToggle_Click);
		imgMini_album.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// onPlayListClick(v);
			}
		});
		RelativeLayout relati = (RelativeLayout) findViewById(R.id.Bar_control_Layout);
		mSilidingUP.setDragView(relati);
		viewPager = (ViewPager) findViewById(R.id.main_view_pager);
		mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
		mIndicator.setCentered(true);
		mIndicator.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageSelected(int position) {
				switch (position) {
				case 0:
					getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
					break;
				default:
					getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
					break;
				}
			}

		});
	}

	/**
	 * Restore preferences
	 */
	private void restorePreferences() {
		SharedPreferences sp = MainActivity.this.getSharedPreferences(MusicService.PREF_NAME, 0);

		// shuffle mode
		setShuffle(sp.getBoolean(MusicService.SETTING_SHUFFLE, false), false);

		// repeat mode
		String rp = sp.getString(MusicService.SETTING_REPEAT, RepeatMode.NoRepeat.toString());
		setRepeatMode(RepeatMode.valueOf(rp), false);
	}

	/**
	 * Save the preferences
	 */
	private void savePreferences() {
		// Save preference
		SharedPreferences sp = MainActivity.this.getSharedPreferences(MusicService.PREF_NAME, 0);
		SharedPreferences.Editor ed = sp.edit();
		if(mPlaylistMgr!=null){
		ed.putBoolean(MusicService.SETTING_SHUFFLE, mPlaylistMgr.isShuffle());
		ed.putString(MusicService.SETTING_REPEAT, mPlaylistMgr.getRepeatMode().toString());
		ed.commit();
		}
	}

	// Click listener của nút Next
	public OnClickListener bt_Next_click = new OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent();
			i.setAction(MusicService.ACTION_NEXT);
			MainActivity.this.startService(i);
		}
	};

	// Click listener của nút play
	public OnClickListener bt_Play_click = new OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent();
			if (MusicService.mState == MediaPlayerState.Playing) {
				i.setAction(MusicService.ACTION_PAUSE);
			}else{
				i.setAction(MusicService.ACTION_PLAY);
			}
			MainActivity.this.startService(i);
		}
	};

	// Click listener của nút previous
	public OnClickListener bt_Previous_click = new OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent();
			i.setAction(MusicService.ACTION_PREVIOUS);
			MainActivity.this.startService(i);
		}
	};

	// click listener of shuffletoggle button
	public OnClickListener bt_ShuffleToggle_Click = new OnClickListener() {

		public void onClick(View v) {
			boolean s = mPlaylistMgr.isShuffle();
			setShuffle(!s, true);
		}
	};

	// click listener of repeattoggle
	public OnClickListener bt_RepeatToggle_Click = new OnClickListener() {

		public void onClick(View v) {
			PlaylistManager.RepeatMode rp = mPlaylistMgr.getRepeatMode();

			if (rp == RepeatMode.NoRepeat)
				setRepeatMode(RepeatMode.RepeatAll, true);
			else if (rp == RepeatMode.RepeatAll)
				setRepeatMode(RepeatMode.RepeatOne, true);
			else
				setRepeatMode(RepeatMode.NoRepeat, true);
		}
	};

	/**
	 * Set repeat mode for mainplayer, update UI also
	 * 
	 * @param rp
	 * @param needtoast
	 *            if true, toast will be shown
	 */
	private void setRepeatMode(RepeatMode rp, boolean needtoast) {
		if (mPlaylistMgr == null)
			return;
		mPlaylistMgr.setRepeatMode(rp);

		if (rp == RepeatMode.RepeatAll) {
			if (needtoast)
				bt_RepeatToggle.setImageResource(R.drawable.ctbh_iconright_click);

		} else if (rp == RepeatMode.RepeatOne) {
			if (needtoast)
				bt_RepeatToggle.setImageResource(R.drawable.ctbh_iconright_click_one);

		} else {
			if (needtoast)
				bt_RepeatToggle.setImageResource(R.drawable.ctbh_iconright);
		}
	}

	/**
	 * set shuffle mode for mainplayer, update also the UI
	 * 
	 * @param s
	 *            Shuffle
	 * @param needtoast
	 *            if true, toast will be shown
	 */
	private void setShuffle(boolean s, boolean needtoast) {
		if (mPlaylistMgr == null)
			return;
		mPlaylistMgr.setShuffle(s);
		if (s) {
			if (needtoast)
				bt_ShuffleToggle.setImageResource(R.drawable.ctbh_iconleft_click);
		} else {
			if (needtoast)
				bt_ShuffleToggle.setImageResource(R.drawable.ctbh_iconleft);
		}
	}

	// Seekbar change listener
	private OnSeekBarChangeListener songProgressBar_changeListener = new OnSeekBarChangeListener() {

		public void onStartTrackingTouch(SeekBar seekBar) {
			songProgressBarIsBeingTouch = true;
		}

		public void onStopTrackingTouch(SeekBar seekBar) {
			songProgressBarIsBeingTouch = false;

			Intent i = new Intent();
			i.setAction(MusicService.ACTION_SEEK);

			Bundle b = new Bundle();
			b.putInt(MusicService.BKEY_PERCENTAGE, seekBar.getProgress());

			i.putExtras(b);
			MainActivity.this.startService(i);
		}

		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

		}
	};

	@Override
	public void onPause() {
		MainActivity.this.unregisterReceiver(mStatusReceiver);
		savePreferences();

		if (MusicService.getState() != MediaPlayerState.Playing) {
			Intent i = new Intent();
			i.setClass(MainActivity.this, MusicService.class);
			MainActivity.this.stopService(i);
		}

		super.onPause();
	}

	@Override
	protected void onStart() {
		super.onStart();
		// register music service status reciever
		try {
			mStatusReceiver = new MusicServiceStatusReceiver();
			IntentFilter filter = new IntentFilter();
			filter.addAction(MusicService.STATUS_BC_NOW_PLAYING);
			filter.addAction(MusicService.STATUS_BC_PLAYTIME);
			filter.addAction(MusicService.STATUS_BC_ALL);
			filter.addAction(MusicService.STATUS_BC_PLAYMODE);
			filter.addAction(MusicService.STATUS_BC_NOWPLAYING_PLAYLIST);
			registerReceiver(mStatusReceiver, filter);
			// request status
			Intent i = new Intent();
			i.setAction(MusicService.REQUEST_STATUS);
			MainActivity.this.startService(i);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		savePreferences();
	}

	@Override
	protected void onResumeFragments() {
		mStatusReceiver = new MusicServiceStatusReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MusicService.STATUS_BC_NOW_PLAYING);
		filter.addAction(MusicService.STATUS_BC_PLAYTIME);
		filter.addAction(MusicService.STATUS_BC_ALL);
		filter.addAction(MusicService.STATUS_BC_PLAYMODE);
		filter.addAction(MusicService.STATUS_BC_NOWPLAYING_PLAYLIST);
		MainActivity.this.registerReceiver(mStatusReceiver, filter);

		// request status
		Intent i = new Intent();
		i.setAction(MusicService.REQUEST_STATUS);
		MainActivity.this.startService(i);
		restorePreferences();
		super.onResumeFragments();
	}

	private class MusicServiceStatusReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Bundle b = intent.getExtras();
			Singleton singleton = Singleton.getInstance();
			if (mPlaylistMgr == null) {
				mPlaylistMgr = new PlaylistManager(singleton.getNowPlayingList());
			}
			if (action.equals(MusicService.STATUS_BC_ALL)) {
				// play-mode buttons
				if (mPlaylistMgr != null) {
					setShuffle(mPlaylistMgr.isShuffle(), false);
					setRepeatMode(mPlaylistMgr.getRepeatMode(), false);
				}
			}
			// Kiểm tra action để thể hiện tên bài hát
			if (action.equals(MusicService.STATUS_BC_NOW_PLAYING) || action.equals(MusicService.STATUS_BC_ALL)) {
				SongObject si = singleton.getCurrentSongObject();
				if (si != null) {
					if (singleton != null) {
						showPanelControl(true);
					}
					updateBarcontrol(si);
					songProgressBar.setEnabled(true);
					songProgressBar1.setEnabled(true);
				} else {
					playing_Title.setText("");
					playing_Artist.setText("");

					txtSong.setText("");
					txtSinger.setText("");

					currentPlayingPosition.setText("");
					currentDuration.setText("");
					currentPlayingPosition1.setText("");
					currentDuration1.setText("");
					songProgressBar.setEnabled(false);
					songProgressBar1.setEnabled(false);
				}
			}

			if (action.equals(MusicService.STATUS_BC_PLAYTIME) || action.equals(MusicService.STATUS_BC_ALL)) {
				// cap nhat seek bar
				int pos = b.getInt(MusicService.BKEY_CURSONG_POSITION);
				int len = b.getInt(MusicService.BKEY_CURSONG_DURATION);
				currentPlayingPosition.setText(UtilMusic.milliSecondsToTimer(pos));
				currentDuration.setText(UtilMusic.milliSecondsToTimer(len));
				currentPlayingPosition1.setText(UtilMusic.milliSecondsToTimer(pos));
				currentDuration1.setText(UtilMusic.milliSecondsToTimer(len));
				if (!songProgressBarIsBeingTouch) {
					songProgressBar.setProgress(UtilMusic.getProgressPercentage(pos, len));
					songProgressBar1.setProgress(UtilMusic.getProgressPercentage(pos, len));
					Drawable ii = getResources().getDrawable(R.drawable.ctbh_icon_timeline);
					songProgressBar.setThumb(ii);
					songProgressBar1.setThumb(ii);
				}
			}

			// Update state of play/pause button
			MediaPlayerState mState = (MediaPlayerState) b.getSerializable(MusicService.BKEY_STATE);
			if (mState == MediaPlayerState.Paused || mState == MediaPlayerState.Stopped) {
				bt_Play.setImageResource(R.drawable.ctbh_pause_icon);
				controlPlay.setImageResource(R.drawable.playbar_button_play);
			} else if (mState == MediaPlayerState.Playing) {
				bt_Play.setImageResource(R.drawable.ctbh_play_icon);
				controlPlay.setImageResource(R.drawable.playbar_button_pause);
			}
		}
	}

	public void SendPlaylistAndplay(ArrayList<SongObject> listSongs, int index) {
		if (mPlaylistMgr != null) {
			if (!BaseEngine.compareList(mPlaylistMgr.getArrayList(), listSongs)) {
				mPlaylistMgr.setArrayList(listSongs);
				send();
				play(listSongs, index);
			} else {
				play(listSongs, index);
			}
		} else {
			mPlaylistMgr = new PlaylistManager(listSongs);
			send();
			play(listSongs, index);
		}
	}

	private void send() {
		Singleton s = Singleton.getInstance();
		s.setPlaylistManager(mPlaylistMgr);
		s.setNowPlayingList(mPlaylistMgr.getArrayList());
		Intent i = new Intent();
		i.setAction(MusicService.SUPPLY_PLAYLIST);
		MainActivity.this.startService(i);
	}

	public void play(ArrayList<SongObject> listSongs, int index) {
		SongObject si = (SongObject) listSongs.get(index);
		Singleton singleton = Singleton.getInstance();
		singleton.setCurrentSongObject(si);
		singleton.setCurrentIndex(index);
		updateBarcontrol(si);
		Intent i1 = new Intent();
		i1.setAction(MusicService.ACTION_PLAY_SPECIFIC_SONG);
		MainActivity.this.startService(i1);
	}
	public void play( int index) {
		SongObject si = (SongObject) mPlaylistMgr.getArrayList().get(index);
		Singleton singleton = Singleton.getInstance();
		singleton.setCurrentSongObject(si);
		singleton.setCurrentIndex(index);
		updateBarcontrol(si);
		Intent i1 = new Intent();
		i1.setAction(MusicService.ACTION_PLAY_SPECIFIC_SONG);
		MainActivity.this.startService(i1);
	}
	public void updateBarcontrol(SongObject si) {
		imgMini_album.setImageResource(R.drawable.cn_avatarbh);
		playing_Title.setText(si.getTXNAME());
		playing_Artist.setText(si.getNAME_SINGERS());
		txtSong.setText(si.getTXNAME());
		txtSinger.setText(si.getNAME_SINGERS());
		if (!si.getFormNet()) {
			Bitmap bm = BitmapFactory.decodeFile(si.getAVATAR());
			if (bm != null) {
				@SuppressWarnings("deprecation")
				BitmapDrawable bmpDraw = new BitmapDrawable(bm);
				imgMini_album.setImageDrawable(bmpDraw);
			}
		} else {
			// new songDetailsServices().execute(si.getSONG_ID());
			// new listCommentService().execute(si.getSONG_ID());
			imageLoader.displayImage(si.getAVATAR(), imgMini_album, options);
		}
		if (TabAdapter == null) {
			MainListeningPlaylistQueue playlistQueue = new MainListeningPlaylistQueue(MainActivity.this, Singleton.getInstance().getNowPlayingList());
			MainListteningContent listteningContent = new MainListteningContent(MainActivity.this, si);
			playlistQueue.adapterQueueAdapter.setPotitionIndicator(Singleton.getInstance().index);
			CommentFragment frComment = new CommentFragment(MainActivity.this, si, TagName.Comment_typeSong);
			TabAdapter = new OfflineTabPageAdapter(getSupportFragmentManager(), playlistQueue, listteningContent, frComment);
			viewPager.setAdapter(TabAdapter);
			mIndicator.setViewPager(viewPager);
		} else {
			TabAdapter.listQueue.update(Singleton.getInstance().getNowPlayingList(), Singleton.getInstance().getCurrentIndex());
			TabAdapter.frMain.update(si);
			TabAdapter.frComment.update(si, "1");
		}
	}

	public void onPlayListClick(View v) {
		if (mPlaylistMgr != null)
			ShowPlayListSongQueue(MainActivity.this, mPlaylistMgr.getArrayList());
	}

	public void ShowPlayListSongQueue(final Activity a, final ArrayList<SongObject> playlist) {
		AlertDialog.Builder builder = new AlertDialog.Builder(a);
		builder.setTitle("Danh sách phát");

		if (playlist == null || playlist.size() == 0) {
			Toast.makeText(a, "Trống!", Toast.LENGTH_SHORT).show();
			return;
		}
		String[] array = new String[playlist.size()];
		for (int i = 0; i < playlist.size(); i++) {
			array[i] = playlist.get(i).getTXNAME();
		}

		builder.setItems(array, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int position) {
				play(playlist, position);
			}
		});
		builder.create().show();
	}

	public void ShowPlayList(final Activity a, final ArrayList<PlaylistObject> playlist) {
		AlertDialog.Builder builder = new AlertDialog.Builder(a);
		builder.setTitle("Danh sách phát");

		if (playlist == null || playlist.size() == 0) {
			Toast.makeText(a, "Trống!", Toast.LENGTH_SHORT).show();
			return;
		}
		String[] array = new String[playlist.size()];
		for (int i = 0; i < playlist.size(); i++) {
			array[i] = playlist.get(i).getTXNAME();
		}

		builder.setItems(array, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int position) {
				Toast.makeText(a, "Trống!", Toast.LENGTH_SHORT).show();
			}
		});
		builder.create().show();
	}

	private static long back_pressed;

	@Override
	public void onBackPressed() {
		if(mCurrentFragment!=null){
			if(mCurrentFragment.getClass().getName()==mFragmentList.get(0).getClass().getName()){
				if (back_pressed + 2000 > System.currentTimeMillis()) {
					finish();
				} else
					Toast.makeText(getBaseContext(), "Press back again to exit!", Toast.LENGTH_SHORT).show();
				back_pressed = System.currentTimeMillis();
			}else if (mFragmentList.size() > 1) {
					showprevousFragment();
			} else {
				if (back_pressed + 2000 > System.currentTimeMillis()) {
					finish();
				} else
					Toast.makeText(getBaseContext(), "Press back again to exit!", Toast.LENGTH_SHORT).show();
				back_pressed = System.currentTimeMillis();
			}
		}else finish();
	}

	public class OfflineTabPageAdapter extends FragmentStatePagerAdapter {
		public MainListeningPlaylistQueue listQueue = null;
		public MainListteningContent frMain = null;
		public CommentFragment frComment = null;

		public OfflineTabPageAdapter(FragmentManager fm, MainListeningPlaylistQueue listView, MainListteningContent frMain, CommentFragment frComment) {
			super(fm);
			this.listQueue = listView;
			this.frMain = frMain;
			this.frComment = frComment;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return null;
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public Fragment getItem(int i) {
			switch (i) {
			case 0:
				return listQueue;
			case 2:
				return frComment;
			default:
				return frMain;
			}
		}
	}
}
